package com.market.plus.core.util;

import java.util.Date;
import java.util.List;

import com.market.plus.core.domain.Friend;
import com.market.plus.core.domain.ModifyedInfo;
import com.market.plus.core.domain.Persistable;
import com.market.plus.core.domain.Status;
import com.market.plus.core.domain.StatusInfo;
import com.market.plus.core.dto.ParticipantDto;
import com.market.plus.core.model.CustomUserDetails;
import com.opm.security.core.util.UserUtil;

public class MarketUtil {

   public static boolean hasIDNotExist(Long id) {
      if (id == null || id == 0)
         return true;
      return false;
   }
   
   public static boolean hasEmptyOrNull(String str) {
      if (str == null || str.trim().length() == 0)
         return true;
      return false;
   }

   public static CustomUserDetails getCustomUserDetails(){
      return (CustomUserDetails) UserUtil.getAuthenticated();
   }

   public static boolean hasGuestView(){
      return ((CustomUserDetails) UserUtil.getAuthenticated()).hasGuestWindow();
   }

   public static ParticipantDto getCurrentLogin(){
      return getCustomUserDetails().getCurrentLoginUser();
   }

   public static ParticipantDto getCurrentView(){
      return getCustomUserDetails().getCurrentViewUser();
   }

   public static boolean hasAuthenticated(){
      return UserUtil.hasAuthenticated();
   }

   public static void setModifyedUser(Object persistableObject, Status status){
      setModifyedUser(persistableObject, status, UserUtil.getCurrentUsername());
   }

   public static void setModifyedUser(Object persistableObject){
      setModifyedUser(persistableObject, null, UserUtil.getCurrentUsername());
   }

   public static void setGuestModifyedUser(Object persistableObject, Status status){
      setModifyedUser(persistableObject, status, UserUtil.getGuestUsername());
   }

   public static Friend getFriend(long friendId, List<Friend> friends){
      for (Friend friend : friends){
         if (friend.getId().longValue() == friendId){
            return friend;
         }
      }
      return null;
   }

   private static void setModifyedUser(Object persistableObject, Status status, String username){
      if (status != null && persistableObject instanceof StatusInfo){
         StatusInfo persistable = (StatusInfo) persistableObject;
         persistable.setStatus(status);
      }
      if (persistableObject instanceof ModifyedInfo){
         Persistable persistable = (Persistable) persistableObject;
         ModifyedInfo modifyedInfo = (ModifyedInfo) persistableObject;
         Date currentDate = DateUtil.getCurrentDate();
         String currentUser = username;
         if (hasIDNotExist(persistable.getId())){
            modifyedInfo.setCreatedDate(currentDate);
            modifyedInfo.setCreatedUser(currentUser);
         }
         modifyedInfo.setModifyedDate(currentDate);
         modifyedInfo.setModifyedUser(currentUser);
      }
   }
}
